package com.itc.bi.easyExcelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.util.ConverterUtils;
import com.alibaba.excel.util.ListUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @BelongsProject: itc-airport-cloud
 * @BelongsPackage: com.itc.bi.easyExcelListener
 * @Author: hecaiy
 * @CreateTime: 2024-09-17  16:58
 * @Description: TODO
 * @Version: 1.0
 */
public class CustomRowHandlers extends AnalysisEventListener<LinkedHashMap<Integer,String>> {
    private Integer pageSize = 0;

    private Map<Integer, String> integerStringMap;

    private List<LinkedHashMap<String,String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(100);

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        integerStringMap = ConverterUtils.convertToStringMap(headMap, context);
    }

    @Override
    public void invoke(LinkedHashMap<Integer, String> data, AnalysisContext context) {
        pageSize++;
        if(pageSize>100){
            throw new RuntimeException("单次读取数据量不能超过100");
//            throw new ExcelAnalysisException("中断");
        }
        LinkedHashMap<String,String> stringObjectLinkedHashMap = new LinkedHashMap<>();
        for (Map.Entry<Integer,String> entry:data.entrySet()){
            Integer key = entry.getKey();
            String value = entry.getValue();
            String title = integerStringMap.get(key);
            stringObjectLinkedHashMap.put(title,value);
        }
        cachedDataList.add(stringObjectLinkedHashMap);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("所有数据解析完成！");
    }

    @Override
    public boolean hasNext(AnalysisContext context) {
        return false; // 返回是否继续读取
    }

    public List<LinkedHashMap<String,String>> getCachedDataList(){
        return cachedDataList;
    }
}

